<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <test-tom></test-tom>
    <test-jerry></test-jerry>
    <div>
        <input type="button" value="销毁" @click="clear">
        <input type="button" value="父组件通过注册中心操作子组件" @click="handle">
    </div>

</div>
<script type="text/javascript">

    Vue.component('test-tom',{
        data:function () {
            return {
                num:0
            }
        },
        template:`<div>
                <span> Tom:{{num}}</span>
                <input type="button" value="add" @click="handle">
            </div>
        `,
        methods:{
            handle:function(){
                eventHub.$emit('jerry-event',1)

            }
        },
        mounted:function(){
            //注册
            eventHub.$on('tom-event',(val)=>{
                this.num+=val;
            })
        }
    })
    Vue.component('test-jerry',{
        data:function () {
            return {
                num:0
            }
        },
        template:`
            <div>
            <span> Jerry:{{num}}</span>
            <input type="button" value="add" @click="handle">
            </div>
        `,
        methods:{
            handle:function(){
                eventHub.$emit('tom-event',2);
            }
        },
        mounted:function(){
            //注册一个事件
            eventHub.$on('jerry-event',(val)=>{
                this.num+=val
            })
        }
    })

    var eventHub=new Vue()
    var app = new Vue({
        el: '#app',
        data: {
            handle:function(){
                eventHub.$emit('tom-event',5);
                eventHub.$emit('jerry-event',10);
            }
        },
        methods:{
            clear:function(){
                eventHub.$off('tom-event');
                eventHub.$off('jerry-event');
            }
        },


    })

</script>

</body>
</html>